package xray

import (
	"gitee.com/gam6it/SecToolkit/utils/http2"
)

const (
	ResultTypeHost      = "host"
	ResultTypeDomain    = "domain"
	ResultTypeService   = "service"
	ResultHostStateUp   = "up"
	ResultHostStateDown = "down"
)

func (xp *XProcess) HostResults(resultType string, limit, offset int) ([]Host, error) {
	var upHosts []Host
	api := xp.client.URI + "api/v2/result/filter/"
	var req = map[string]interface{}{
		"limit":       limit,
		"offset":      offset,
		"xprocess_id": xp.Id,
		"result_type": resultType,
	}
	type host struct {
		IpAddress string `json:"ip_address"`
		State     string `json:"state"`
		OsMatches string `json:"os_matches"`
	}
	type resp struct {
		Count  int    `json:"count"`
		Result []host `json:"result"`
	}
	var result resp
	err := request(http2.MethodPost, api, xp.client.Token, &result, http2.JsonParam(req), http2.TimeOut(xp.client.TimeOut))
	if err != nil {
		return upHosts, err
	}
	var filterOption []FilterOption
	for _, h := range result.Result {
		if h.State == ResultHostStateUp {
			filterOption = append(filterOption, FilterOption{
				Content:   h.IpAddress,
				IsPartial: false,
			})
		}
	}
	_, upHosts, err = xp.client.HostFilter(HostFilterOption{
		Limit:  0,
		Offset: 0,
		IP:     filterOption,
	})
	return upHosts, nil
}
